<template>
  <el-input class="money-input" :has-error="hasError" value="value" v-model="displayValue" :placeholder="placeholder"
    :disabled="disabled" @change="onInputChanged">
    <template slot="append">元</template>
  </el-input>
</template>
<script>
export default {
  name: 'MoneyInput',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: [Number, String],
    placeholder: String,
    disabled: Boolean
  },
  watch: {
    value(val) {
      this.displayValue = (val / 100.0).toFixed(2)
    }
  },
  data() {
    return {
      displayValue: (this.value / 100.0).toFixed(2),
      oldInputValue: this.displayValue,
      hasError: false
    }
  },
  methods: {
    onInputChanged(val) {
      if (Number(val)<0) {
        this.displayValue = (0 / 100.0).toFixed(2);
        this.hasError = false
        return;
      }


      this.oldInputValue = this.displayValue;
      if (!isNaN(new Number(val))) {
        this.hasError = false;
        let nums = this.displayValue.split('.');
        if (nums.length > 1) {
          if (nums[1].length > 2) {
            this.displayValue = parseFloat(this.displayValue).toFixed(2);
          }
        }
        this.$emit("change", (val * 100).toFixed(0));
      } else {
        this.hasError = true;
      }
    }
  }
}
</script>
<style >
.el-input-group__append {
  padding: 0 8px;
}

.money-input .el-input__inner[has-error="true"] {
  border: 1px solid #F56C6C;
}
</style>
